//
//  ChatSetUpViewController.m
//  PigMarket
//
//  Created by mac on 2019/6/15.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "ChatSetUpViewController.h"
#import "SystemSetingCell.h"
#import "ModifyFriendNameViewController.h"
#import "ChatSetUpFooterView.h"
#import "ChatComplaintViewController.h"

@interface ChatSetUpViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    TIMFriend *_friendProfile;
}
/**
 myTableView
 */
@property (nonatomic , strong) UITableView *myTableView;
/**
 dataArr
 */
@property (nonatomic , strong) NSArray *dataArr;

/**
 footer
 */
@property (nonatomic , strong) ChatSetUpFooterView *footerView;
/**
 是否在黑名单
 */
@property (nonatomic , assign) NSNumber *switchStatus;

@end

@implementation ChatSetUpViewController
@synthesize friendProfile = _friendProfile;

#pragma mark - view life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"聊天详情";
    [self setUpNav];
    [self setUpView];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
}

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

#pragma mark - init method
- (void)setUpNav {
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"nav_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonClick)];
}


- (void)setUpView {
    [self initView];
    [self initLayout];
    [self initAction];
    [self initData];
}
- (void)initView {
    [self.view addSubview:self.myTableView];
}

- (void) initLayout {
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
}

- (void) initAction {

}
- (void)initData {
    
    //后台要求调取此接口，获取是否在黑名单的状态
    NSString *myMemberNum = [NSString stringWithFormat:@"%@",[UserInfoDataProvider sharedInstance].userInfo.memberNum];
    @weakify(self);
    [[[PigMarketApi sharedInstance] getChatUserInfoWithMemberNum:self.friendProfile.identifier myMemberNum:myMemberNum] subscribeNext:^(ChatUserInfo * _Nullable chatUserInfo) {
        @strongify(self);
        self.switchStatus = chatUserInfo.blackIf;
        [self refreshData];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}
- (void)refreshData {
    
    NSNumber *switchStatus = self.switchStatus ? self.switchStatus : @0;
    
    NSString *name = self.friendProfile.remark;
    if (self.friendProfile.remark.length == 0) {
        name = @"未命名";
    }
    self.dataArr = @[@[@{@"title":@"备注豚友名称",@"detail":name}],
                     @[@{@"title":@"加入黑名单",@"detail":switchStatus},
                       @{@"title":@"投诉",@"detail":@""}]];
    [self.myTableView reloadData];

}
#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 2;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 1) {
        return 123;
    } else {
        return 0.001;
    }
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 1) {
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 123)];
        
        self.footerView = [[ChatSetUpFooterView alloc] initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, 113)];
        [self.footerView.quitBtn setTitle:@"删除好友" forState:UIControlStateNormal];
        [self.footerView.clearBtn addTarget:self action:@selector(clearChatRecordClick) forControlEvents:UIControlEventTouchUpInside];
        [self.footerView.quitBtn addTarget:self action:@selector(deleteFriendClick) forControlEvents:UIControlEventTouchUpInside];
        [bgView addSubview:self.footerView];
        return bgView;
    } else {
        return [[UIView alloc] init];
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SystemSetingCell *cell = [SystemSetingCell cellWithTableView:tableView];
    if (indexPath.section == 0 && indexPath.row == 0) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    } else if (indexPath.section == 1 && indexPath.row == 1){
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    if (self.dataArr.count > 0) {
        [cell configChatCellWithDataDic:self.dataArr[indexPath.section][indexPath.row] indexPath:indexPath];
    }
   
    //加入黑名单
    @weakify(self);
    [cell setMySwitchBlock:^(BOOL switchStuts) {
        if (switchStuts) {
            //加入
            @strongify(self);
            [self showAddBlackListAlert];
        } else {
            //取消
            [self showDeleteBlackListAlert];
        }
        
    }];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
        {
            if (indexPath.row == 0) {
                //备注豚友名称
                ModifyFriendNameViewController *vc = [[ModifyFriendNameViewController alloc] init];
                vc.identifier = self.friendProfile.identifier;
                @weakify(self);
                [vc setRefreshChatSetUpDataBock:^(NSString *remark) {
                    @strongify(self);
                    self.friendProfile.remark = remark;
                    [self refreshData];
                }];
                [self.navigationController pushViewController:vc animated:YES];
            }
         }
            break;
        case 1:
        {
            if (indexPath.row == 1) {//投诉
                ChatComplaintViewController *vc = [[ChatComplaintViewController alloc] init];
                vc.identifier = self.friendProfile.identifier;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
            break;
        
        default:
            break;
    }
}
#pragma mark - target action
- (void)leftButtonClick {
    [self.navigationController popViewControllerAnimated:YES];
}
//清空聊天记录
- (void)clearChatRecordClick {
    @weakify(self);
    [[AlertAction sharedInstance] showAlertWithTitle:nil message:@"是否确定清空聊天记录" confirmBtnTitle:@"确定" confirmBlock:^{
        @strongify(self);
        BOOL deleteStatus = [[TIMManager sharedInstance] deleteConversationAndMessages:TIM_C2C receiver:self.friendProfile.identifier];
        if (deleteStatus) {
            [self toastWithContent:@"删除成功"];
        } else {
            [self toastWithContent:@"删除失败"];
        }
    } cancelBlock:nil];

}
//删除好友
- (void)deleteFriendClick {
    @weakify(self);
    [[AlertAction sharedInstance] showAlertWithTitle:nil message:@"是否删除好友" confirmBtnTitle:@"确定" confirmBlock:^{
        @strongify(self);
        [self deleteTIMFriend];

    } cancelBlock:nil];
}
#pragma mark - private method

#pragma mark - ------------添加黑名单------------------
- (void)showAddBlackListAlert {
    SystemSetingCell *cell = (SystemSetingCell *)[self.myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];

    [[AlertAction sharedInstance] showAlertWithTitle:nil message:@"您确定要加入黑名单吗？" confirmBtnTitle:@"确定" confirmBlock:^{
        [self addTIMBlackList];

    } cancelBlock:^{
        cell.mySwitch.on = NO;

    }];
}
- (void)addTIMBlackList{
    @weakify(self);
    [[TIMFriendshipManager sharedInstance] addBlackList:@[self.friendProfile.identifier] succ:^(NSArray<TIMFriendResult *> *results) {
        @strongify(self);
        [self addBlackListRequest];
    } fail:^(int code, NSString *msg) {
        @strongify(self);
        [self toastWithContent:msg];
    }];
}
- (void)addBlackListRequest {
    @weakify(self);
    [[[PigMarketApi sharedInstance] addBlackListWithMyMemberNum:[UserInfoDataProvider sharedInstance].userInfo.memberNum memberNum:self.friendProfile.identifier] subscribeNext:^(NSNull * _Nullable x) {
        @strongify(self);
        [self toastWithContent:@"黑名单添加成功"];
    } error:^(NSError * _Nullable error) {
        
        @strongify(self);
        [self handlingError:error];
    }];
}
#pragma mark - ------------删除黑名单------------------
- (void)showDeleteBlackListAlert {
    SystemSetingCell *cell = (SystemSetingCell *)[self.myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
    
    [[AlertAction sharedInstance] showAlertWithTitle:nil message:@"您确定要删除黑名单吗？" confirmBtnTitle:@"确定" confirmBlock:^{
        [self deleteTIMBlackList];

    } cancelBlock:^{
        cell.mySwitch.on = YES;

    }];
}
- (void)deleteTIMBlackList {
    @weakify(self);
    [[TIMFriendshipManager sharedInstance] deleteBlackList:@[self.friendProfile.identifier] succ:^(NSArray<TIMFriendResult *> *results) {
        @strongify(self);
        [self deleteBlackListRequest];
    } fail:^(int code, NSString *msg) {
        @strongify(self);
        [self toastWithContent:msg];
    }];
}
- (void)deleteBlackListRequest {
    @weakify(self);
    [[[PigMarketApi sharedInstance] deleteBlackListWithMyMemberNum:[UserInfoDataProvider sharedInstance].userInfo.memberNum memberNum:self.friendProfile.identifier] subscribeNext:^(NSNull * _Nullable x) {
        @strongify(self);
        [self toastWithContent:@"黑名单删除成功"];
    } error:^(NSError * _Nullable error) {
        
        @strongify(self);
        [self handlingError:error];
    }];
}
#pragma mark - ------------删除好友------------------

- (void)deleteTIMFriend {
    @weakify(self);
    [[TIMFriendshipManager sharedInstance] deleteFriends:@[self.friendProfile.identifier] delType:TIM_FRIEND_DEL_BOTH succ:^(NSArray<TIMFriendResult *> *results) {
        @strongify(self);
        [self deleteFriendRequest];
    } fail:^(int code, NSString *msg) {
        @strongify(self);
        [self toastWithContent:msg];
    }];
}
- (void)deleteFriendRequest {
    @weakify(self);
    [[[PigMarketApi sharedInstance] deleteChatFriendWithMemberId:[UserInfoDataProvider sharedInstance].userInfo.memberId friendId:@([self.friendProfile.identifier intValue])] subscribeNext:^(NSNull * _Nullable x) {
        @strongify(self);
        [self toastWithContent:@"删除成功"];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}
#pragma mark - getter and setter
- (UITableView *)myTableView {
    if (!_myTableView) {
        _myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableView.rowHeight = 56;
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
    }
    return _myTableView;
}
- (NSArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [[NSArray alloc] init];
    }
    return _dataArr;
}
@end
